package br.pucrio.inf.aaaong.models.form.converters.atomic;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.ResourceBundle;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.pucrio.inf.aaaong.models.form.errors.FormError;

@Convert(Calendar.class)
public class FormCalendarConverter implements Converter<Calendar>, FormConverter<Calendar> {
	private static final String INVALID_DATE_FORMAT_MESSAGE = "deve estar no formato 'dd/mm/aaaa'.";
	private static final String DATE_FORMAT = "dd/MM/yyyy";

	@Override
	public Calendar convert(String dateStr, Class<? extends Calendar> klass,
			ResourceBundle rb) {
		if (dateStr == null || dateStr.isEmpty()) return null;
		SimpleDateFormat formatter = getFormatter();
		Calendar date = Calendar.getInstance();
		try {
			date.setTime(formatter.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException("Calendar conversion error");
		}
		return date;
	}

	public Calendar convert(String dateStr) {
		return convert(dateStr, null, null);
	}
	
	public boolean canConvert(String dateStr) {
		if (dateStr == null || dateStr.isEmpty()) return true;
		if (!dateStr.matches("^\\d{2}/\\d{2}/\\d{4}$")) return false;
		try {
			SimpleDateFormat formatter = getFormatter();
			formatter.parse(dateStr);
			return true;
		} catch (ParseException e) {
			return false;
		}
	}
	
	private SimpleDateFormat getFormatter() {
		return new SimpleDateFormat(DATE_FORMAT);
	}

	@Override
	public String getConversionErrorMessage() {
		return INVALID_DATE_FORMAT_MESSAGE;
	}

}
